package org.rcy.framework.rpc.config;

import org.rcy.framework.rpc.base.RpcServer;
import org.rcy.framework.rpc.base.ServiceScanner;
import org.rcy.framework.rpc.monit.DefaultHealthServiceImpl;
import org.rcy.framework.rpc.monit.HealthService;
import org.rcy.framework.rpc.registry.RpcRegistry;
import org.rcy.framework.rpc.registry.RpcServiceScanner;
import org.rcy.framework.rpc.registry.SpringRpcServerStarter;
import org.rcy.framework.rpc.registry.SpringThriftRpcServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@EnableConfigurationProperties({ RpcProperties.class })
@Order(20)
public class ServerAutoConfiguration {

	@Autowired
	private RpcProperties rpcProperties;

//	@Autowired
//	private CuratorFramework zkClient;

	@Bean
	@Order(1)
	public ServiceScanner serviceScanner() {
		return new RpcServiceScanner(rpcProperties.getServer());
	}

//	@Bean
//	@Order(2)
//	public ZooKeeperServerRegistry serverRegistry() {
//		return new ZooKeeperServerRegistry(zkClient);
//	}
	
	@Bean
	@Order(3)
	@ConditionalOnMissingBean(HealthService.class)
	public HealthService healthService() {
		return new DefaultHealthServiceImpl();
	}

	@Bean
	@Order(4)
	public RpcServer rpcServer(ServiceScanner serviceScanner, RpcRegistry registry) {
		RpcProperties.ServerProperties serverProperties = rpcProperties.getServer();
		SpringThriftRpcServer rpcServer = new SpringThriftRpcServer(serverProperties);
		rpcServer.setServiceScanner(serviceScanner);
		rpcServer.setRegistry(registry);
		rpcServer.setWeight(serverProperties.getWeight());
		return rpcServer;
	}

	@Bean
	@Order(5)
	public SpringRpcServerStarter rpcServerStarter(RpcServer rpcServer) {
		return new SpringRpcServerStarter(rpcServer);
	}

}